import './index.less';
import React, { useState, useEffect } from 'react';
import ZhCN from 'antd/lib/locale/zh_CN';
import {
  Table,
  Input,
  Button,
  Badge,
  message,
  Modal,
  Divider,
  Card,
  Form,
  Pagination,
  Row,
  ConfigProvider,
  Space,
} from 'antd';
import columnsData from './data';
import {
  AtomicServiceServiceAdd,
  AtomicServiceServiceDelete,
  AtomicServiceServiceEdit,
  AtomicServiceServiceList,
  AtomicServiceServiceView,
} from '../api/AtomicService';

const index = () => {
  // 列表请求函数
  const getDatas = (valOne: any, valTwo: any) => {
    try {
      AtomicServiceServiceList(valOne, valTwo).then((val) => {
        setDatas(val.data);
        setListTotal(val.pagination.totalSize);
      });
    } catch (error) {}
  };

  // 列表添加函数
  const addDatas = (valOne: any) => {
    try {
      AtomicServiceServiceAdd(valOne).then((val) => {
        // console.log(val);
        refreshList();
      });
    } catch (error) {}
  };

  // 列表项编辑函数
  const editDatas = (valOne: any) => {
    try {
      AtomicServiceServiceEdit(valOne).then((val) => {
        // console.log(val);
        refreshList();
      });
    } catch (error) {}
  };

  // 列表项删除函数
  const deleteDatas = (valOne: any) => {
    try {
      AtomicServiceServiceDelete(valOne).then((val) => {
        // console.log(val);
        refreshList();
      });
    } catch (error) {}
  };

  // 列表项查看函数
  const viewDatas = (valOne: any) => {
    try {
      AtomicServiceServiceView(valOne).then((val) => {
        // console.log(val);
        viewForm.setFieldsValue(val.data);
      });
    } catch (error) {}
  };
  // 列表数据
  const [datas, setDatas] = useState([]);
  // 删除提示框显示状态
  const [isModalVisible, setIsModalVisible] = useState(false);
  // 删除提示框显示状态
  const [id, setId] = useState('');
  // 删除列表项ID
  const [deleteid, setDeleteid] = useState();
  // 查询条件应用ID
  const [appId, setAppId] = useState('');
  // 查询条件服务名
  const [choreographyServiceName, setChoreographyServiceName] = useState('');
  // 查询条件方法名
  const [choreographyMethodName, setChoreographyMethodName] = useState('');
  // 查询条件当前页
  const [currentPageNo, setCurrentPageNo] = useState(1);
  // 查询条件页大小
  const [pageSize, setPageSize] = useState(10);
  // 列表总条数
  const [listTotal, setListTotal] = useState(1);
  // 用户添加模态框显示状态
  const [addModal, setAddModal] = useState(false);
  // 用户编辑模态框显示状态
  const [editModal, setEditModal] = useState(false);
  // 添加用户数据表单验证
  const addFormRef: any = React.createRef();
  // 用户数据修改表单交互
  const [editForm] = Form.useForm();
  // 用户查看列表项交互
  const [viewForm] = Form.useForm();
  // 查看模态框是否显示
  const [viewModal, setViewModal] = useState(false);

  // table表格组合操作
  const columns = columnsData;
  // 定义操作行
  const columnsActionRender: any = {
    action: (text: any, record: any, index: number) => (
      <div>
        <a onClick={() => viewUser(record.id)}>查看</a>
        <Divider type="vertical" />
        <a onClick={() => editUser(record)}>修改</a>
        <Divider type="vertical" />
        <a onClick={() => handleRemove(record.id)}>删除</a>
      </div>
    ),
  };
  // 定义状态行
  const columnsStatusRender: any = {
    status: (text: any, record: any, index: number) => (
      <div>
        {record.status === 0 ? (
          <Badge status="processing" text="启用" />
        ) : record.status === 1 ? (
          <Badge status="error" text="禁用" />
        ) : (
          ''
        )}
      </div>
    ),
  };
  // 表格头部数据
  columns.forEach((item: any) => {
    if (item.dataIndex === 'action')
      item.render = columnsActionRender[item.dataIndex];
    if (item.dataIndex === 'status')
      item.render = columnsStatusRender[item.dataIndex];
  });

  // 添加服务编排模态框确认按钮
  const addServerOk = () => {
    // console.log('添加成功');
  };

  // 查看模态框确认按钮
  const viewOk = () => {
    setViewModal(false);
  };

  // 数据加载
  useEffect(() => {
    getDatas(
      { appId, choreographyServiceName, choreographyMethodName },
      { currentPageNo, pageSize },
    );
  }, []);

  // 刷新列表
  const refreshList = () => {
    getDatas(
      { appId, choreographyServiceName, choreographyMethodName },
      { currentPageNo, pageSize },
    );
  };

  // 重置
  const reset = () => {
    setAppId('');
    setChoreographyServiceName('');
    setChoreographyMethodName('');
    setCurrentPageNo(1);
    setPageSize(10);
    refreshList();
  };

  /**
   * 显示模态框提示是否删除
   * @param id 用户id
   */
  const handleRemove = (id: string) => {
    setDeleteid(id);
    setIsModalVisible(true);
  };

  // 确定删除用户数据
  const handleOk = () => {
    // console.log(deleteid);
    setIsModalVisible(false);
    const Id = deleteid;
    deleteDatas({ Id });
  };

  // 添加
  const addModalOk = async () => {
    try {
      // 非空验证
      const validate = await addFormRef.current.validateFields();
      const param = await addFormRef.current.getFieldsValue();
      // console.log(param); // 传入的参数
      addDatas(param);
      setAddModal(false);
      addFormRef.current.resetFields();
    } catch (err) {
      // console.log(err);
    }
  };

  /**
   * 编辑-点击打开模态框-回显
   * @param item 行对象数据
   */
  const editUser = async (item: any) => {
    setEditModal(true);
    // console.log(item);
    editForm.setFieldsValue(item);
  };

  // 查看
  const viewUser = (id: string) => {
    setViewModal(true);
    // console.log(id);
    viewDatas({ id });
  };

  // 保存编辑值-修改
  const editUserOK = () => {
    setEditModal(false);
    const param = editForm.getFieldsValue();
    // console.log(param);
    editDatas(param);
  };

  return (
    <div className="bg-gray">
      <div className="flex p-3 mb-2 bg-white searchTable">
        <Form layout="inline">
          <Space size={[8, 16]} wrap>
            <Form.Item label="应用ID:">
              <Input
                onChange={(event: any) => {
                  setAppId(event.target.value);
                }}
                value={appId}
              />
            </Form.Item>
            <Form.Item label="服务名:">
              <Input
                onChange={(event: any) => {
                  setChoreographyServiceName(event.target.value);
                }}
                value={choreographyServiceName}
              />
            </Form.Item>
            <Form.Item label="方法名:">
              <Input
                onChange={(event: any) => {
                  setChoreographyMethodName(event.target.value);
                }}
                value={choreographyMethodName}
              />
            </Form.Item>
            <div style={{ paddingLeft: '58px' }}>
              <Button
                style={{ marginRight: 8 }}
                onClick={() => {
                  refreshList();
                }}
                type="primary"
              >
                查询
              </Button>
              <Button onClick={reset}>重置</Button>
            </div>
          </Space>
        </Form>
      </div>

      <Card
        title="原子服务"
        className="tableTitle"
        extra={
          <Button
            type="primary"
            onClick={() => {
              setAddModal(true);
            }}
          >
            {' '}
            +添加
          </Button>
        }
        bordered={false}
      >
        <Table
          columns={columns}
          dataSource={datas}
          scroll={{ x: 1500 }}
          pagination={false}
          rowKey={(datas: { id: string }) => datas.id}
        />
        <Row justify="end" style={{ marginTop: '20px', paddingBottom: '10px' }}>
          <ConfigProvider locale={ZhCN}>
            <Pagination defaultCurrent={1} total={listTotal} />
          </ConfigProvider>
        </Row>
      </Card>
      {/* 删除模态框 */}
      <Modal
        cancelText="取消"
        okText="确认"
        title="提示"
        visible={isModalVisible}
        onOk={handleOk}
        key={'update'}
        onCancel={() => {
          setIsModalVisible(false);
        }}
      >
        是否确定删除本条数据？
      </Modal>

      {/* 查看模态框 */}
      <Modal
        forceRender={true}
        cancelText="取消"
        okText="确定"
        title="查看"
        key={'view'}
        visible={viewModal}
        onOk={viewOk}
        onCancel={() => {
          setViewModal(false);
        }}
      >
        <Form form={viewForm} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }}>
          <Form.Item label="应用id" name="appId">
            <Input disabled />
          </Form.Item>
          <Form.Item label="服务名" name="serviceName">
            <Input disabled />
          </Form.Item>
          <Form.Item label="方法名" name="choreographyMethodName">
            <Input disabled />
          </Form.Item>
          <Form.Item label="接口全类名" name="className">
            <Input disabled />
          </Form.Item>
          <Form.Item label="请求报文" name="requestMessage">
            <Input disabled />
          </Form.Item>
          <Form.Item label="响应报文" name="responseMessage">
            <Input disabled />
          </Form.Item>
          <Form.Item label="描述" name="remark">
            <Input disabled />
          </Form.Item>
          <Form.Item label="版本号" name="version">
            <Input disabled />
          </Form.Item>
        </Form>
      </Modal>

      {/* 新增模态框 */}
      <Modal
        destroyOnClose
        cancelText="取消"
        okText="新增"
        title="用户新增"
        visible={addModal}
        onOk={addModalOk}
        key={'add'}
        onCancel={() => {
          setAddModal(false);
        }}
      >
        <Form ref={addFormRef} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }}>
          <Form.Item label="应用id" name="appId" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item
            label="服务名"
            name="choreographyServiceName"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="方法名"
            name="choreographyMethodName"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="接口全类名"
            name="className"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item label="请求报文" name="requestMessage">
            <Input />
          </Form.Item>
          <Form.Item label="响应报文" name="responseMessage">
            <Input />
          </Form.Item>
          <Form.Item label="描述" name="remark">
            <Input />
          </Form.Item>
          <Form.Item label="版本号" name="version" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
        </Form>
      </Modal>

      {/* 修改模态框 */}
      <Modal
        destroyOnClose
        cancelText="取消"
        okText="修改"
        title="用户编辑"
        visible={editModal}
        onOk={editUserOK}
        key={'edit'}
        onCancel={() => {
          setEditModal(false);
        }}
      >
        <Form form={editForm} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }}>
          <Form.Item
            className="d-none"
            label="id"
            name="id"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item label="应用id" name="appId">
            <Input />
          </Form.Item>
          <Form.Item label="服务名" name="choreographyServiceName">
            <Input />
          </Form.Item>
          <Form.Item label="方法名" name="choreographyMethodName">
            <Input />
          </Form.Item>
          <Form.Item label="接口全类名" name="className">
            <Input />
          </Form.Item>
          <Form.Item label="请求报文" name="requestMessage">
            <Input />
          </Form.Item>
          <Form.Item label="响应报文" name="responseMessage">
            <Input />
          </Form.Item>
          <Form.Item label="描述" name="remark">
            <Input />
          </Form.Item>
          <Form.Item label="版本号" name="version">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};
export default index;
